﻿using System;
using System.Collections.Generic;
using System.Linq;
using csvm.coordinator.contract;
using csvm.datamodel.contract;
using csvm.fileadapter.contract;
using csvm.pagebuilder.contract;
using csvm.recordbuilder.contract;

namespace Coordinator {
    public class Coordinator : ICoordinator{
        private readonly IFileAdapter fileAdapter ;
        private readonly IRecordBuilder recordBuilder;
        private readonly IPageBuilder pageBuilder;

        public Coordinator(IFileAdapter fileAdapter, IRecordBuilder recordBuilder, IPageBuilder pageBuilder) {
            this.fileAdapter = fileAdapter;
            this.recordBuilder = recordBuilder;
            this.pageBuilder = pageBuilder;
        }

        public IEnumerable<Page> LoadPages(string filename, out Record header) {
            var rows = fileAdapter.ReadFile(filename);
            var records = recordBuilder.BuildRecords(rows);
            header = records.First();
            var pages = pageBuilder.BuildPages(records.Skip(1));
            return pages;
        }

        event Action<double> ICoordinator.OnProgressChanged {
            add { fileAdapter.OnProgressChanged += value; }
            remove { fileAdapter.OnProgressChanged -= value; }
        }
    }
}
